package com.icinfo.cloud.provider.peripheralinterface.xzzf.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.dto.DingUserResultDto;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.dto.OrgInfoResultDto;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.dto.ZfPeopleDataDto;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.vo.ZfAndManageUserInfoVO;
import com.icinfo.cloud.xzcf.provider.member.line.dto.LineDTO;
import com.icinfo.cloud.xzcf.provider.member.zfpeople.dto.ZfCert;
import com.icinfo.cloud.xzcf.provider.member.zfpeople.dto.ZfPeopleBaseInfoVO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 描述：行政执法接口服务实现类
 *
 * @author xiangyuyu
 * @date 2022/4/8 11:53
 */
@Service
@Slf4j
public class XzzfInterfaceServiceImpl implements IXzzfInterfaceService {

    @Value("${member.url}")
    private String memberUrl;

    @Value("${member.api.getPeopleBaseInfo}")
    private String getUserInfoApi;
    @Value("${member.api.getLineListByLineCodes}")
    private String getLineListByLineCodes;
    @Value("${member.api.getUserByZwdAccountId}")
    private String getUserByZwdAccountIdApi;
    @Value("${member.api.getOrgInfoByUnicode}")
    private String getOrgInfoByUnicodeApi;
    @Value("${member.api.getUser}")
    private String getUserApi;
    @Value("${member.api.getZfPeopleSignDataByUserInfo}")
    private String getZfPeopleSignDataByUserInfoApi;
    @Value("${member.api.getUsersByUserIds}")
    private String getUsersByUserIdsUrl;

    /**
     * 描述：获取执法人员信息
     *
     * @param baseInfoRequest TODO：入参格式最好是优化成实体类
     * @return List<ZfPeopleBaseInfoVO>
     * @author xiangyuyu
     * @date 2022-04-08 13:54
     */
    @Override
    public List<ZfPeopleBaseInfoVO> getZfPeopleList(JSONObject baseInfoRequest) {
//        log.info("getZfPeopleList start... param-baseInfoRequest:{}", baseInfoRequest);
        String response="";
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(baseInfoRequest);
        //log.info("getZfPeopleList start... param-baseInfoRequest:{}", param);
        try {
            response = HttpUtil.createPost(memberUrl.concat(getUserInfoApi)).setConnectionTimeout(3000).setReadTimeout(3000).addHeaders(headers).body(param).execute().body();
        }catch (Exception e){
            System.out.println("获取执法人员异常,入参:"+param);
            return new ArrayList<>();
        }
       //        log.info("getZfPeopleList response:{}",response);
        JSONObject info= new JSONObject();
        try {
            info = JSONObject.parseObject(response);
        } catch (Exception e) {
            log.warn("返回的值不是json格式："+response);
            return new ArrayList<>();
        }
        List<ZfPeopleBaseInfoVO> listDtos = new ArrayList<>();
        String code = "code";
        int th = 200;
        if (th == info.getInteger(code)) {
            PageResponse<JSONObject> users = JSON.parseObject(info.getString("data"), PageResponse.class);
            for (JSONObject object : users.getData()) {
                ZfPeopleBaseInfoVO vo=JSON.parseObject(JSON.toJSONString(object), ZfPeopleBaseInfoVO.class);
                if(StringUtils.isNotBlank(object.getString("zwdAccountId"))){
                    vo.setDingDingId(object.getString("zwdAccountId"));
                }/*else{
                    try {
                        String phoneNum = vo.getPhone();
                        String dingId = DingDingUtil.getAccountIdByMobile(phoneNum);
                        vo.setDingDingId(dingId);
                    }catch (Exception e){
                        vo.setDingDingId("");
                    }
                }*/
                listDtos.add(vo);
            }
        }
//        log.info("getZfPeopleList end... result-listDtos:{}", listDtos);
        return listDtos;
    }

    /**
     * 获取执法人员和管理人员用户信息（包含政务钉钉用户id）
     * @param userIdList
     * @return
     * @author mahan
     * @date 2022-10-18 15:54
     */
    @Override
    public List<ZfAndManageUserInfoVO> getZfAndManageUsersByUserIds(List<String> userIdList){
        log.info("----------参数：用户Id列表：{}------------", JSONObject.toJSONString(userIdList));
        Map<String, String> headers = HeaderUtil.headerInfo();
        //header添加授权
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        headers.put(Constant.AUTH_HEADER_KEY, request.getHeader(Constant.AUTH_HEADER_KEY));
        String response = HttpUtil.createPost(memberUrl.concat(getUsersByUserIdsUrl)).addHeaders(headers).body(JSONObject.toJSONString(userIdList)).execute().body();
        JSONObject resJONObject;
        try {
            resJONObject = JSONObject.parseObject(response);
        } catch (Exception e) {
            log.warn("-----------请求接口返回错误信息：{}---------------", response);
            return CollUtil.newArrayList();
        }
        if(resJONObject != null && resJONObject.getInteger("code") == 200){
            log.info("-----------请求接口成功：{}---------------", response);
            List<ZfAndManageUserInfoVO> list = JSONObject.parseArray(resJONObject.getString("data"), ZfAndManageUserInfoVO.class);
            return list;
        }else {
            log.info("-----------请求接口返回错误信息：{}---------------", response);
        }
        return CollUtil.newArrayList();
    }

    public static void main(String[] args) {
        String userId = "179070793739665408,36553";
        JSONObject baseInfoRequest = new JSONObject();
        List<String> userIds = Arrays.asList(userId.split(","));
        baseInfoRequest.put("userIds", userIds);
        Map<String, String> headers = HeaderUtil.headerInfo();
        headers.put("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJseWYxODg2ODg3NjI3MCIsImF1ZCI6IndlYiIsImNyZWF0ZWQiOjE2NjYwOTAyNjcxNjYsImFwcElkIjpudWxsLCJpc3MiOiJpY2luZm8uY24iLCJleHAiOjE2NjY2OTUwNjd9.zTpY6cOKIl0dXyU_kI_xr7GpbQy9mwF8x-QoUDh0YlrOS99U7HDnMUMnk5HdE4zBUJv-nzqnPS1jXiyevAwh5Q");
        String response = HttpUtil.createPost("http://192.168.1.201:9999/api/v2/member/user/getUsersByUserIds").addHeaders(headers).body(JSONObject.toJSONString(userIds)).execute().body();
        JSONObject resJONObject = JSONObject.parseObject(response);
        List<ZfAndManageUserInfoVO> list = JSONObject.parseArray(resJONObject.getString("data"), ZfAndManageUserInfoVO.class);

        System.out.println(response);
    }

    /**
     * 描述：获取执法证编号信息
     *
     * @param userId 用户Id
     * @return String 执法证编号信息
     * @author xiangyuyu
     * @date 2022-04-08 16:58
     */
    @Override
    public String getLawEnforcementCertWithUserId(String userId) {
        log.info("getLawEnforcementCertWithUserId start... param-userId:{}", userId);
        if (ObjectUtils.isEmpty(userId)) {
            throw new BusinessException("获取执法证编号信息时出现异常-未指定用户id");
        }
        String lawEnforcementCert = null;
        JSONObject requestInfo = new JSONObject();
        List<String> userIdList = new ArrayList<>();
        userIdList.add(userId);
        requestInfo.put("userIds", userIdList);
        List<ZfPeopleBaseInfoVO> userInfoList = getZfPeopleList(requestInfo);
        //有效证书列表
        List<String> effectiveCertNumberList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(userInfoList) && userInfoList.size() > 0) {
            ZfPeopleBaseInfoVO zfPeopleBaseInfoVO = userInfoList.get(Constant.INTEGER_0);
            List<ZfCert> zfCertList = zfPeopleBaseInfoVO.getZfCertList();
            if (!ObjectUtils.isEmpty(zfCertList) && zfCertList.size() > 0) {
                for (ZfCert c : zfCertList) {
                    String status = c.getStatus();
                    if (Constant.STRING_0.equals(status)) {
                        effectiveCertNumberList.add(c.getZfCertNo());
                    }
                }
            } else {
                log.warn("未匹配到执法证编号信息 userId:{}", userId);
            }
        } else {
            log.warn("未匹配到执法人员信息 userId:{}", userId);
        }
        if (effectiveCertNumberList.size() > 0) {
            lawEnforcementCert = effectiveCertNumberList.toString().replace("[", "").replace("]", "");
        } else {
            log.warn("未匹配到有效的执法证编号信息 userId:{}", userId);
        }
        log.info("getLawEnforcementCertWithUserId end... result-lawEnforcementCert:{}", lawEnforcementCert);
        return lawEnforcementCert;
    }

    /**
     * 描述：获取执法证编号信息
     *
     * @param userId 用户Id
     * @param orgCode 部门编码
     * @return String 执法证编号信息
     * @author xiangyuyu
     * @date 2022-04-08 16:58
     */
    @Override
    public String getLawEnforcementCertWithUserIdAndOrgCode(String userId, String orgCode) {
        log.info("getLawEnforcementCertWithUserId start... param-userId:{}", userId);
        if (ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(orgCode)) {
            throw new BusinessException("获取执法证编号信息时出现异常-未指定用户id及部门编码");
        }
        String lawEnforcementCert = null;
        JSONObject requestInfo = new JSONObject();
        List<String> userIdList = new ArrayList<>();
        List<String> orgCodeList = new ArrayList<>();
        userIdList.add(userId);
        orgCodeList.add(orgCode);
        requestInfo.put("userIds", userIdList);
        requestInfo.put("orgCodes", orgCodeList);
        List<ZfPeopleBaseInfoVO> userInfoList = getZfPeopleList(requestInfo);
        //有效证书列表
        List<String> effectiveCertNumberList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(userInfoList) && userInfoList.size() > 0) {
            ZfPeopleBaseInfoVO zfPeopleBaseInfoVO = userInfoList.get(Constant.INTEGER_0);
            List<ZfCert> zfCertList = zfPeopleBaseInfoVO.getZfCertList();
            if (!ObjectUtils.isEmpty(zfCertList) && zfCertList.size() > 0) {
                for (ZfCert c : zfCertList) {
                    String status = c.getStatus();
                    if (Constant.STRING_0.equals(status)) {
                        effectiveCertNumberList.add(c.getZfCertNo());
                    }
                }
            } else {
                log.warn("未匹配到执法证编号信息 userId:{}", userId);
            }
        } else {
            log.warn("未匹配到执法人员信息 userId:{}", userId);
        }
        if (effectiveCertNumberList.size() > 0) {
            lawEnforcementCert = effectiveCertNumberList.toString().replace("[", "").replace("]", "");
        } else {
            log.warn("未匹配到有效的执法证编号信息 userId:{}", userId);
        }
        log.info("getLawEnforcementCertWithUserId end... result-lawEnforcementCert:{}", lawEnforcementCert);
        return lawEnforcementCert;
    }


    /**
     * 描述：根据条线code获取条线信息
     *
     * @return {@link LineDTO }
     * @author shishengyao
     * @date 2022/06/29
     */
    @Override
    public LineDTO getLineInfoByLineCode(String lineCode){
        log.info("getLineListByLineCodes start... param-baseInfoRequest:{}", getLineListByLineCodes);
        Map<String, String> headers = HeaderUtil.headerInfo();
        List<String> linecodes=new ArrayList<>();
        linecodes.add(lineCode);
        JSONObject requestInfo = new JSONObject();
        requestInfo.put("codes", linecodes);
        String param = JSON.toJSONString(linecodes);
        String response = HttpUtil.createPost(memberUrl.concat(getLineListByLineCodes)).addHeaders(headers).body(param).execute().body();
        log.info("getLineListByLineCodes response:{}",response);
        JSONObject info = JSONObject.parseObject(response);
        List<LineDTO > lineDTOList = new ArrayList<>();
        String code = "code";
        int th = 200;
        if (th == info.getInteger(code)) {
            List<JSONObject> lineList = JSON.parseObject(info.getString("data"), List.class);
            for (JSONObject object : lineList) {
                lineDTOList.add(JSON.parseObject(JSON.toJSONString(object), LineDTO.class));
            }
        }
        log.info("getLineListByLineCodes end... result-lineDTOList:{}", lineDTOList);
        if (lineDTOList.size()>0){
            return  lineDTOList.get(0);
        } else {
            log.warn("未匹配到有效的条线信息 lineCode:{}", lineCode);
        }
        return null;
    }

    /**
     * 描述： 根据浙政钉id获取用户信息
     *
     * @author: zhengqiang
     * @date: 2022/8/19
     * @param: ZwdingAccountId
     * @return {@link DingUserResultDto}
     **/
    @Override
    public DingUserResultDto getUserByZwdAccountId(String ZwdingAccountId) {
        Map<String, Object> urlParam = Collections.singletonMap("zwdingAccountId", ZwdingAccountId);
        log.info("getUserByZwdAccountId start... param:{}", urlParam);
        String response = HttpUtil.createGet(memberUrl.concat(getUserByZwdAccountIdApi)).form(urlParam).execute().body();
        log.info("getUserByZwdAccountId response:{}", response);
        if (ObjectUtils.isEmpty(response)) {
            return null;
        }
        DingUserResultDto dingUserResultDto = JSONObject.parseObject(response, DingUserResultDto.class);
        return dingUserResultDto;
    }

    /**
     * 描述： 根据统一社会信用代码获取机构信息
     *
     * @author: zhengqiang
     * @date: 2022/8/19
     * @param: unicode
     * @return {@link OrgInfoResultDto}
     **/
    @Override
    public OrgInfoResultDto getOrgInfoByUnicode(String unicode) {
        Map<String, Object> urlParam = Collections.singletonMap("unicode", unicode);
        log.info("getOrgInfoByUnicode start... param:{}", urlParam);
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createGet(memberUrl.concat(getOrgInfoByUnicodeApi)).addHeaders(headers).form(urlParam).execute().body();
        log.info("getOrgInfoByUnicode response:{}", response);
        if (ObjectUtils.isEmpty(response)) {
            return null;
        }
        Result result = JSONObject.parseObject(response, Result.class);
        if (HttpStatus.HTTP_OK == result.getCode() && !ObjectUtils.isEmpty(result.getData())) {
            OrgInfoResultDto orgInfoResultDto = JSONObject.parseObject(result.getData().toString(), OrgInfoResultDto.class);
            return orgInfoResultDto;
        }
        return null;
    }

    /**
     * 描述： 根据用户id获取手机号
     *
     * @author: zhengqiang
     * @date: 2022/8/24
     * @param: userId
     * @return {@link String}
     **/
    @Override
    public String getUserPhoneByUserId(String userId) {
        Map<String, Object> urlParam = Collections.singletonMap("userId", userId);
        Map<String, String> headers = HeaderUtil.headerInfo();
        log.info("getUser start... param:{}", urlParam);
        try {
            String response = HttpUtil.createGet(memberUrl.concat(getUserApi)).addHeaders(headers).form(urlParam).execute().body();
            log.info("getUser response:{}", response);
            if (ObjectUtils.isEmpty(response)) {
                return null;
            }
            Result result = JSONObject.parseObject(response, Result.class);
            if (HttpStatus.HTTP_OK == result.getCode() && !ObjectUtils.isEmpty(result.getData())) {
                JSONObject jsonObject = JSONObject.parseObject(result.getData().toString());
                return jsonObject.getString("phone");
            }
        } catch (HttpException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 描述： 根据用户id获取签名base64
     *
     * @author: zhengqiang
     * @date: 2022/8/30
     * @param: userId
     * @return {@link String}
     **/
    @Override
    public ZfPeopleDataDto getZfPeopleSignDataByUserInfo(String userId) {
        Map<String, Object> urlParam = Collections.singletonMap("userId", userId);
        log.info("getZfPeopleSignDataByUserId start... param:{}", urlParam);
        try {
            Map<String, String> headers = HeaderUtil.headerInfo();
            String response = HttpUtil.createGet(memberUrl.concat(getZfPeopleSignDataByUserInfoApi)).addHeaders(headers).form(urlParam).execute().body();
            log.info("getZfPeopleSignDataByUserId response:{}", response);
            if (ObjectUtils.isEmpty(response)) {
                return null;
            }
            Result result = JSONObject.parseObject(response, Result.class);
            if (HttpStatus.HTTP_OK == result.getCode() && !ObjectUtils.isEmpty(result.getData())) {
                ZfPeopleDataDto peopleDataDto = JSONObject.parseObject(result.getData().toString(), ZfPeopleDataDto.class);
                return peopleDataDto;
            }
        } catch (HttpException e) {
            log.warn("获取签名异常(getZfPeopleSignDataByUserId): {}", e);
            e.printStackTrace();
        }
        return null;
        //todo 重庆暂时写死
        /*ZfPeopleDataDto peopleDataDto =new ZfPeopleDataDto();
        peopleDataDto.setSignData("http://192.168.2.223:8888/group1/M00/00/00/wKgC32SIVBmAXn5HAAAGbCGrh0w622.png");
        peopleDataDto.setZfCertNo("123");
        return peopleDataDto;*/
    }

}
